package com.shuqi.activity.viewport;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.CatalogAdapter;
import com.shuqi.activity.adapter.PayCatalogAdapter;
import com.shuqi.activity.viewport.LeftSliderLayout.OnLeftSliderLayoutStateListener;
import com.shuqi.application.CataLogCache;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Constant;
import com.shuqi.common.PayTheme;
import com.shuqi.common.utils.CheckTxtCatalogTool;
import com.shuqi.common.utils.CheckTxtCatalogTool.OnCheckingListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookCataLogDao.CatalogChangerListener;
import com.shuqi.database.dao.impl.TxtCatalogDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.bean.BookContentLineInfo;
import com.shuqi.model.bean.BookData;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

public class CataLogLayout extends FrameLayout implements CatalogChangerListener {

    private CatalogAdapter mCatalogAdapter; // 本地书籍目录
    private PayCatalogAdapter mPayCatalogAdapter; // 收费书籍目录
    public LeftSliderLayout mLeftSliderLayout;
    // private ExpandableListView mPayCatalogListView; // 网络目录ListView（二级）
    private ListView mPayCatalogListView;
    private ListView mlocalCatalogListView; // 本地目录ListView
    private CheckTxtCatalogTool mCatalogTool; // 本地TXT目录检索
    private TextView mCatLogPercentTxt;
    private View mCatLogProgressView;
    /** 目录标题 */
    private TextView bookNameText;
    private View mLoading; // 网络目录加载
    private View mErrorView; // 获取目录错误
    private ImageView mErrorIcon;
    private TextView mErrorText;
    private TextView mErrorRetry;
    /** 目录阴影 */
    private ImageView mCatalogShadow;

    private String mBookId; // 当前目录BookId
    @Deprecated
    private String mSourceId;// 视情况用此变量
    private String mCurrentChapterId;

    private String mLocalFilePath;

    /** 收费目录 */
    private List<BookCataLog> mPayCatalogList;
    /** 神马目录 */
    private BookCataLog mShenMaCatalogInfo;

    private List<BookContentInfo> mLocalCatalogList;

    private long lastUpdateTime = 0;

    private onViewChangeListener mListener;

    public interface onViewChangeListener {
        void onJumpSeekBarDisable();

        void onJumpSeekBarEnable();
    }

    public void setOnViewChangeListener(onViewChangeListener l) {
        this.mListener = l;
    }

    public void notifyJumpBarDisable() {
        if (mListener != null)
            mListener.onJumpSeekBarDisable();
    }

    public void notifyJumpSeekBarEnable() {
        if (mListener != null)
            mListener.onJumpSeekBarEnable();
    }

    public CataLogLayout(Context context) {
        super(context);
        init();
    }

    public CataLogLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CataLogLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_catalog_layout, this);
        initView();
    }


    private void initView() {
        mLeftSliderLayout = (LeftSliderLayout) findViewById(R.id.main_slider_layout);
        mPayCatalogListView = (ListView) findViewById(R.id.pay_catalog_listView);
        mlocalCatalogListView = (ListView) findViewById(R.id.loc_catalog_listView);
        mCatLogPercentTxt = (TextView) findViewById(R.id.bookcataloglocal_tv_check_tip1);
        bookNameText = (TextView) findViewById(R.id.catalog_title);
        mCatLogProgressView = findViewById(R.id.catLog_progress_view);
        mLoading = findViewById(R.id.include_loading);
        // 获取目录错误

        mErrorView = findViewById(R.id.include_error);
        mErrorIcon = (ImageView) findViewById(R.id.error_icon);
        mErrorText = (TextView) findViewById(R.id.error_text);
        mErrorRetry = (TextView) findViewById(R.id.error_retry);

        mCatalogShadow = (ImageView) findViewById(R.id.catalog_shadow);
        mCatalogShadow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                close();
                StatisticsUtils.onEvent(getContext(), StatisticsEventID.CATALOGLAYOUT_CLOSE);
            }
        });
        showLoading();
    }

    /**
     * 修改listview默认的滑动条
     */
    private void setScrollBar(final ListView listview, int imgId) {
        if (Util.getOSVersion() >= 19) {
            // setScrollBar_forSDK19(listview);
            return;
        }
        try {
            Field f = AbsListView.class.getDeclaredField("mFastScroller");
            f.setAccessible(true);
            Object o = f.get(listview);
            f = f.getType().getDeclaredField("mThumbDrawable");
            f.setAccessible(true);
            Drawable drawable = (Drawable) f.get(o);
            drawable = getResources().getDrawable(imgId);
            f.set(o, drawable);
        } catch (Exception e) {
            Log4an.e("CataLogLayout", e.toString());
        }
    }

    /**
     * 修改android 4.4 listview默认的滑动条 暂时不可行 setScrollBar setScrollBar_forSDK19
     */
    private void setScrollBar_forSDK19(final ListView listview) {
        listview.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_FLING:// 快速滑动
                        // 这里如果 直接setFastScrollEnabled(true) 不生效
                        break;
                    case SCROLL_STATE_IDLE:// 静止不动
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:// 缓慢滑动
                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {}
        });
        return;
    }

    public void open(int bookType, String bookName, int totalLength,
            List<BookContentLineInfo> curLines, int lineIndex, String chapterId,
            List<BookContentInfo> cataLogList) {        
        mLeftSliderLayout.open();
//        Log4an.i("yjd", "已经进入目录...");
        int themeIndex = PayTheme.getCurrentTheme(getContext());
        initCatalog(bookType, bookName, totalLength, curLines, lineIndex, chapterId, cataLogList,
                themeIndex);
        setCatLogTheme(themeIndex);
        StatisticsUtils.onEvent(getContext(), StatisticsEventID.BOOKCONTENT_CATALOG);
    }

    /** 仅仅是为了拿到目录数据 by Linyuren */
    public void onleGetCalotyData(int bookType, List<BookContentInfo> cataLogList) {
        onlyGetCatalogData(bookType, cataLogList);
    }

    public boolean close() {
        final boolean isOpen = mLeftSliderLayout.isOpen();
        if (isOpen)
            mLeftSliderLayout.close();
        return isOpen;
    }

    private void initCatalog(int bookType, String bookName, int totalLength,
            List<BookContentLineInfo> curLines, int lineIndex, String chapterId,
            List<BookContentInfo> cataLogList, int themeIndex) {
//        Log4an.i("yjd", "bookType=" + bookType+",bookName="+bookName+",chapterId="+chapterId);
        /** 书籍名称 */
        showBookName(bookName);
        /** 目录数据 */
        if (bookType == Constant.BOOKTYPE_PAY || bookType == Constant.BOOKTYPE_ORDER_PAY) {
            mCurrentChapterId = chapterId;
            showNetCatalog();
        } else {
            if (bookType != Constant.BOOKTYPE_TXT) {
                mLocalCatalogList = cataLogList;
            }
            showLocalCatalog(themeIndex);

            int position = 0;
            if (bookType == Constant.BOOKTYPE_TXT || bookType == Constant.BOOKTYPE_UMD) {
                position = getLocationIndex(totalLength, curLines, lineIndex);
            } else if (bookType == Constant.BOOKTYPE_EPUB) {
//                Log4an.i("yjd", "【epub】chapterId=" + chapterId);
                position = Integer.parseInt(chapterId);
//                Log4an.i("yjd", "【epub】position=" + position);
            } else if (bookType == Constant.BOOKTYPE_BAG) {
                position = getBookBagPosition(chapterId);
            } else {
                position = getLocationIndex(totalLength, curLines, lineIndex);
            }

            if (mLocalCatalogList != null && position >= 0 && position < mLocalCatalogList.size()) {
                mlocalCatalogListView.setSelection(position);
                mCatalogAdapter.setSelection(position);
                mCatalogAdapter.notifyDataSetChanged();
            }
        }
    }

    /** 获取目录数据 by Linyuren */
    private void onlyGetCatalogData(int bookType, List<BookContentInfo> cataLogList) {
        if (bookType != Constant.BOOKTYPE_TXT) {
            mLocalCatalogList = cataLogList;
        }
    }

    /** 定位书包目录 */
    private int getBookBagPosition(String cid) {
        if (mLocalCatalogList != null && mLocalCatalogList.size() > 0) {
            int size = mLocalCatalogList.size();
            for (int i = 0; i < size; i++) {
                if (mLocalCatalogList.get(i).getCurChapterCid().equals(cid)) {
                    return i;
                }
            }
        }
        return 0;
    }

    private int getLocationIndex(int totalLength, List<BookContentLineInfo> curLines, int lineIndex) {
        Log4an.e("yyy", "totalLength=" + totalLength + ",lineIndex=" + lineIndex
                + ",curLines is null=" + (curLines == null ? true : curLines.size()));
        if (mLocalCatalogList == null || mLocalCatalogList.size() == 0) {
            return -1;
        }

        int positon = 0;
        List<BookContentInfo> catalogList = mLocalCatalogList;
        if (curLines == null || curLines.size() <= lineIndex || curLines.get(lineIndex) == null) {
            return -1;
        }
        int keyIndex = curLines.get(lineIndex).getFirstIndex();
        if (keyIndex < 0) {
            keyIndex = 0;
        }

        if (keyIndex == 0)
            return positon;

        if (keyIndex >= catalogList.get(catalogList.size() - 1).getStartIndex()) {
            return catalogList.size() - 1;
        }

        for (int i = 0; i < catalogList.size() - 1; i++) {
            if (keyIndex >= catalogList.get(i).getStartIndex()
                    && keyIndex < catalogList.get(i + 1).getStartIndex()) {
                positon = i;
                break;
            }
        }
        Log4an.e("yyy", "positon=" + positon);
        return positon;
    }

    private void setCatLogTheme(int themeIndex) {

        int textColor = Constant.READ_FONT_COLORS[themeIndex];
        int bgColor = Constant.CATLOG_BG_COLORS[themeIndex];
        int dividerId = Constant.CATLOG_DV_LINE[themeIndex];

        findViewById(R.id.catLog_root).setBackgroundColor(bgColor);
        findViewById(R.id.text_divider).setBackgroundResource(dividerId);
        if (mPayCatalogListView != null) {
            mPayCatalogListView.setBackgroundColor(bgColor);
            mPayCatalogListView.setDivider(getResources().getDrawable(dividerId));
        }
        if (mlocalCatalogListView != null) {
            mlocalCatalogListView.setBackgroundColor(bgColor);
            mlocalCatalogListView.setDivider(getResources().getDrawable(dividerId));
        }
        int mImageID = Constant.CATALOG_BOOKMARK_FAST_BAR_IMAGE[1];
        if (PayTheme.PAY_THEME == themeIndex) {// 夜间
            mImageID = Constant.CATALOG_BOOKMARK_FAST_BAR_IMAGE[0];
        } else {
            mImageID = Constant.CATALOG_BOOKMARK_FAST_BAR_IMAGE[1];
        }
        setScrollBar(mlocalCatalogListView, mImageID);
        setScrollBar(mPayCatalogListView, mImageID);

        mCatLogPercentTxt.setTextColor(textColor);
        bookNameText.setTextColor(textColor);

        if (mLoading != null) {
            mLoading.setBackgroundColor(bgColor);
        }

        if (mCatLogProgressView != null) {
            mCatLogProgressView.setBackgroundColor(bgColor);
        }
        if (bookNameText != null) {
            bookNameText.setBackgroundColor(bgColor);
        }
    }

    public interface OnCatalogScanListener {
        public void onScanFinish(List templist);
    }

    public void cataLogScan(int type, String filePath, String bookId, String userId,
            String curChapterId, String uid, String sourceId, final OnCatalogScanListener listener) {
        mLocalFilePath = filePath;
        mBookId = bookId;
        mSourceId = sourceId;
        if (type == Constant.BOOKTYPE_TXT) {
            if (!SharedPreferenceUtil.getFileCatalogTool(getContext(), filePath)) {
                mCatalogTool = CheckTxtCatalogTool.getInstance();
                if (!mCatalogTool.isChecking(filePath)) {
                    notifyJumpBarDisable();
                    mCatalogTool.check(filePath, getContext(), new OnCheckingListener() {
                        @Override
                        public void onUpdate(final List<BookContentInfo> templist,
                                final int percent, String checkedName) {
                            ShuqiApplication.getApplicationHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    updateTxtCatLog(new ArrayList<BookContentInfo>(templist),
                                            percent);
                                }
                            });
                        }

                        @Override
                        public void onFinish(List<BookContentInfo> finalList,
                                final boolean isRealFinish) {
                            ShuqiApplication.getApplicationHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if (isRealFinish) {
                                        catLogFinish();
                                        SharedPreferenceUtil.setFileCatalogTool(getContext(),
                                                mLocalFilePath, true,
                                                TxtCatalogDao.getInstance().isRunOld);
                                        notifyJumpSeekBarEnable();
                                    }
                                }
                            });

                            mCatalogTool = null;
                            if (listener != null)
                                listener.onScanFinish(finalList);
                        }
                    });
                    ShuqiApplication.getApplicationHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            catLogStart();
                        }
                    });
                } else {
                    mLocalCatalogList =
                            TxtCatalogDao.getInstance().getTxtCatalogListByFilePath(filePath);
                    if (listener != null)
                        listener.onScanFinish(mLocalCatalogList);
                }
            } else {
                mLocalCatalogList =
                        TxtCatalogDao.getInstance().getTxtCatalogListByFilePath(filePath);
                if (listener != null)
                    listener.onScanFinish(mLocalCatalogList);
            }
        } else if (type == Constant.BOOKTYPE_PAY || type == Constant.BOOKTYPE_ORDER_PAY) {
            if (bookId != null) {
                Log4an.i("yjd", "bookId=" + bookId);
                final List<BookCataLog> tmpCataLogList =
                        BookCataLogDao.getInstance().getAllCatalog(uid, bookId, sourceId);
                Log4an.i("yjd", "tmpCataLogList=" + (tmpCataLogList == null));
                mPayCatalogList =
                        tmpCataLogList == null ? new ArrayList<BookCataLog>() : tmpCataLogList;
                CataLogCache.getInstance().initCache(bookId, sourceId, uid, mPayCatalogList);
            }
        } else if (type == Constant.BOOKTYPE_NET) {
            List<BookCataLog> tmpNetCataLogList =
                    BookCataLogDao.getInstance().getAllCatalog(uid, bookId, sourceId);
            CataLogCache.getInstance().initCache(bookId, sourceId, uid, tmpNetCataLogList);
            mShenMaCatalogInfo =
                    BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId,
                            curChapterId);
        }

    }

    private void updateTxtCatLog(List<BookContentInfo> tempList, int percent) {
        if (tempList != null && tempList.size() > 0) {
            mLocalCatalogList = tempList;
            if (System.currentTimeMillis() - lastUpdateTime > 5000) {
                if (mPayCatalogListView != null && mLeftSliderLayout.isOpen()) {
                    if (mCatalogAdapter == null) {
                        mCatalogAdapter = new CatalogAdapter(getContext(), tempList);
                    } else {
                        mCatalogAdapter.setData(tempList);
                    }
                    mCatalogAdapter.notifyDataSetChanged();
                }
                lastUpdateTime = System.currentTimeMillis();
            }
        }
        if (mCatLogPercentTxt != null && percent >= 0 && percent <= 100) {
            mCatLogPercentTxt.setText("正读取章节进度 : " + percent + "%");
            if (percent == 100) {
                catLogFinish();
            }
        }
    }


    private void catLogFinish() {
        mCatLogProgressView.setVisibility(View.GONE);
    }

    private void catLogStart() {
        mCatLogProgressView.setVisibility(View.VISIBLE);
    }

    /**
     * 显示本地书籍目录
     */
    private void showLocalCatalog(int themeIndex) {
        if (mLocalCatalogList != null && mLocalCatalogList.size() > 0) {
            mErrorView.setVisibility(View.GONE);
            if (mCatalogAdapter == null) {
                mCatalogAdapter = new CatalogAdapter(getContext(), mLocalCatalogList);
            } else {
                mCatalogAdapter.setData(mLocalCatalogList);
            }
        } else {
            showCheckError(themeIndex);
        }

        mlocalCatalogListView.setVisibility(View.VISIBLE);
        mPayCatalogListView.setVisibility(View.GONE);
        mLoading.setVisibility(View.GONE);
        if (mCatalogAdapter != null) {
            mCatalogAdapter.setTheme();
        }
        mlocalCatalogListView.setAdapter(mCatalogAdapter);
    }

    /**
     * 显示网络书籍目录
     */
    private void showNetCatalog() {

        if (mPayCatalogList == null) {
            showLoading();
            return;
        }

        if (mPayCatalogList.size() > 0) {
            if (mPayCatalogAdapter == null) {
                mPayCatalogAdapter = new PayCatalogAdapter(getContext(), mPayCatalogList);
            }
            mPayCatalogAdapter.setList(mPayCatalogList);

            mErrorView.setVisibility(View.GONE);
            mlocalCatalogListView.setVisibility(View.GONE);
            mPayCatalogListView.setVisibility(View.VISIBLE);
            mLoading.setVisibility(View.GONE);

            mPayCatalogAdapter.setTheme();
            mPayCatalogListView.setAdapter(mPayCatalogAdapter);

            int position = mPayCatalogAdapter.getPosition(mCurrentChapterId);
            mPayCatalogListView.setSelection(position);
            mPayCatalogAdapter.setSelectorChapterId(mCurrentChapterId);
            mPayCatalogAdapter.notifyDataSetChanged();
        } else {
            mLoading.setVisibility(View.VISIBLE);
            mlocalCatalogListView.setVisibility(View.GONE);
        }
    }

    /**
     * 显示加载数据View
     */
    private void showLoading() {
        mlocalCatalogListView.setVisibility(View.GONE);
        mPayCatalogListView.setVisibility(View.GONE);
        mLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 显示书籍名称
     * 
     * @param bookName
     */
    private void showBookName(String bookName) {
        if (!TextUtils.isEmpty(bookName)) {
            bookNameText.setText(bookName);
            bookNameText.setVisibility(View.VISIBLE);
        } else {
            bookNameText.setVisibility(View.GONE);
        }
    }

    @Deprecated
    private void showNetError() {
        mErrorView.setVisibility(View.VISIBLE);
        mErrorIcon.setImageResource(R.drawable.icon_network);
        mErrorText.setText(R.string.net_error_text);
        mErrorRetry.setVisibility(View.VISIBLE);
    }

    /**
     * 没有目录数据时错误界面
     * 
     * @param themeIndex 主题索引
     */
    private void showCheckError(int themeIndex) {
        mErrorView.setVisibility(View.VISIBLE);
        mErrorIcon.setImageResource(Constant.CATALOG_NO_DATA_IMAGE[themeIndex]);
        mErrorText.setTextColor(Constant.CATALOG_NO_DATA_TEXT[themeIndex]);

        mErrorText.setText(R.string.bookcontent_catalog_empty_tip);
        mErrorRetry.setVisibility(View.GONE);
    }



    public String getTheSourceLink(String uid, String sourceId, String bookId, String curChapterCid) {
        Log4an.e("liyizhe", "获取来源uid=" + uid + ",sourceID=" + sourceId + ",bid=" + bookId + ",cid="
                + curChapterCid);
        mShenMaCatalogInfo =
                BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId,
                        curChapterCid);
        if (mShenMaCatalogInfo != null) {
            Log4an.e("liyizhe", "获取来源url=" + mShenMaCatalogInfo.getChapterSourceUrl());
            return mShenMaCatalogInfo.getChapterSourceUrl();
        }
        return null;
    }

    public void setOnItemClickListener(OnItemClickListener itemItemClickListener) {
        mlocalCatalogListView.setOnItemClickListener(itemItemClickListener);
        mPayCatalogListView.setOnItemClickListener(itemItemClickListener);
        // mPayCatalogListView.setOnChildClickListener(childClickListener);

    }

    public void setOnLeftSliderLayoutListener(OnLeftSliderLayoutStateListener l) {
        mLeftSliderLayout.setOnLeftSliderLayoutListener(l);
    }

    public void stopCheck() {
        if (mCatalogTool != null) {
            mCatalogTool.stopCheck();
        }

    }

    public List<BookContentInfo> getLocalCatalogList() {
        return mLocalCatalogList;
    }



    public BookCataLog getInfoFromCataLog(int groupPosition, int childPosition) {
        return mPayCatalogAdapter.getInfoFromCataLog(groupPosition, childPosition);
    }

    public void resetChapterPayModel2NoPay(String chapterId) {
        if (mPayCatalogAdapter != null)
            mPayCatalogAdapter.resetChapterPayState2NoPay(chapterId);
    }

    public int getStartIndex(int position) {
        return mCatalogAdapter.mListInfos.get(position).getStartIndex();
    }

    public int getEndIndex(int position) {
        return mCatalogAdapter.mListInfos.get(position).getEndIndex();
    }

    public String getFilePath(int position) {
        return mCatalogAdapter.mListInfos.get(position).getFliePath();
    }

    public String getChapterPath(int position) {
        return mCatalogAdapter.mListInfos.get(position).getChapterpath();
    }

    public String getCurChapterId(int position) {
        return mCatalogAdapter.mListInfos.get(position).getCurChapterCid();
    }

    public void initPayCataLog(BookData catalog, int pageCount) {
        this.mPayCatalogList = catalog.getInfos();
    }

    @Override
    public void onCatalogChanger(String bookId, String sourceId, String uid) {
        if (mBookId != null && mBookId.equals(bookId)) {
            mPayCatalogList = BookCataLogDao.getInstance().getAllCatalog(uid, bookId, sourceId);
            if (mPayCatalogList != null && mPayCatalogList.size() > 0) {
                CataLogCache.getInstance().initCache(bookId, sourceId, uid, mPayCatalogList);
                ShuqiApplication.getApplicationHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        showNetCatalog();
                    }
                });
            }
        }
    }
}
